import { BaseAPI } from './baseAPI';
import type {
  SearchQuery,
  SearchResponse,
  SearchSuggestion,
  TrendingSearch,
  SearchHistory,
  VoiceSearchConfig,
  ImageSearchParams,
} from '@/types';

/**
 * 搜索 API 服务类
 */
class SearchAPI extends BaseAPI {
  /**
   * 执行搜索
   */
  async search(query: SearchQuery): Promise<SearchResponse> {
    const cacheKey = `search_${JSON.stringify(query)}`;

    const response = await this.requestWithDeduplication(cacheKey, async () => {
      return await this.post<SearchResponse>('/api/search', query);
    });
    return response.data;
  }

  /**
   * 获取搜索建议
   */
  async getSuggestions(query: string, limit = 10): Promise<SearchSuggestion[]> {
    if (!query.trim()) {
      return [];
    }

    const cacheKey = `suggestions_${query}_${limit}`;

    const response = await this.requestWithDeduplication(cacheKey, async () => {
      return await this.get<SearchSuggestion[]>('/api/search/suggestions', {
        q: query,
        limit,
      });
    });
    return response.data;
  }

  /**
   * 获取热门搜索
   */
  async getTrendingSearches(limit = 20): Promise<TrendingSearch[]> {
    const response = await this.get<TrendingSearch[]>('/api/search/trending', {
      limit,
    });
    return response.data;
  }

  /**
   * 获取搜索历史
   */
  async getSearchHistory(userId: string, limit = 50): Promise<SearchHistory[]> {
    const response = await this.get<SearchHistory[]>(`/api/users/${userId}/search-history`, {
      limit,
    });
    return response.data;
  }

  /**
   * 保存搜索历史
   */
  async saveSearchHistory(userId: string, query: string, resultCount: number): Promise<void> {
    await this.post(`/api/users/${userId}/search-history`, {
      query,
      resultCount,
      timestamp: Date.now(),
    });
  }

  /**
   * 删除搜索历史
   */
  async deleteSearchHistory(userId: string, historyId?: string): Promise<void> {
    if (historyId) {
      await this.delete(`/api/users/${userId}/search-history/${historyId}`);
    } else {
      await this.delete(`/api/users/${userId}/search-history`);
    }
  }

  /**
   * 语音搜索
   */
  async voiceSearch(audioBlob: Blob, config: VoiceSearchConfig): Promise<string> {
    const formData = new FormData();
    formData.append('audio', audioBlob);
    formData.append('config', JSON.stringify(config));

    const response = await this.post<{ transcript: string }>('/api/search/voice', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    return response.data.transcript;
  }

  /**
   * 图片搜索
   */
  async imageSearch(params: ImageSearchParams): Promise<SearchResponse> {
    const formData = new FormData();

    if (params.file) {
      formData.append('image', params.file);
    } else if (params.url) {
      formData.append('imageUrl', params.url);
    } else if (params.base64) {
      formData.append('imageBase64', params.base64);
    }

    // 添加其他参数
    Object.entries(params).forEach(([key, value]) => {
      if (key !== 'file' && key !== 'url' && key !== 'base64' && value !== undefined) {
        formData.append(key, String(value));
      }
    });

    const response = await this.post<SearchResponse>('/api/search/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    return response.data;
  }

  /**
   * 获取相关搜索
   */
  async getRelatedQueries(query: string, limit = 10): Promise<string[]> {
    const response = await this.get<string[]>('/api/search/related', {
      q: query,
      limit,
    });
    return response.data;
  }

  /**
   * 搜索自动完成
   */
  async autocomplete(query: string, limit = 10): Promise<string[]> {
    if (!query.trim()) {
      return [];
    }

    const cacheKey = `autocomplete_${query}_${limit}`;
    
    const response = await this.requestWithDeduplication(cacheKey, async () => {
      return await this.get<string[]>('/api/search/autocomplete', {
        q: query,
        limit,
      });
    });
    return response.data;
  }

  /**
   * 搜索拼写检查
   */
  async spellCheck(query: string): Promise<{
    corrected: string;
    confidence: number;
    suggestions: string[];
  }> {
    const response = await this.post<{
      corrected: string;
      confidence: number;
      suggestions: string[];
    }>('/api/search/spell-check', { query });

    return response.data;
  }

  /**
   * 高级搜索
   */
  async advancedSearch(params: {
    query: string;
    exactPhrase?: string;
    anyWords?: string;
    excludeWords?: string;
    site?: string;
    fileType?: string;
    dateRange?: {
      start: Date;
      end: Date;
    };
    language?: string;
    region?: string;
  }): Promise<SearchResponse> {
    const response = await this.post<SearchResponse>('/api/search/advanced', params);
    return response.data;
  }

  /**
   * 搜索统计
   */
  async getSearchStats(query: string): Promise<{
    totalResults: number;
    searchTime: number;
    relatedQueries: string[];
    popularFilters: Array<{
      name: string;
      count: number;
    }>;
  }> {
    const response = await this.get<{
      totalResults: number;
      searchTime: number;
      relatedQueries: string[];
      popularFilters: Array<{
        name: string;
        count: number;
      }>;
    }>('/api/search/stats', { q: query });

    return response.data;
  }

  /**
   * 报告搜索问题
   */
  async reportSearchIssue(params: {
    query: string;
    issueType: 'irrelevant' | 'spam' | 'broken_link' | 'inappropriate' | 'other';
    description?: string;
    resultId?: string;
  }): Promise<void> {
    await this.post('/api/search/report', params);
  }

  /**
   * 搜索反馈
   */
  async submitSearchFeedback(params: {
    query: string;
    rating: number; // 1-5
    feedback?: string;
    helpful?: boolean;
  }): Promise<void> {
    await this.post('/api/search/feedback', params);
  }
}

// 创建搜索 API 实例
export const searchAPI = new SearchAPI();

// 导出类型和实例
export { SearchAPI };
export default searchAPI;
